package com.hwpt.chesedemo.presentation.screen

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import com.hwpt.chesedemo.presentation.component.ChessMove
import com.hwpt.chesedemo.presentation.component.ChessScreen
import com.hwpt.chesedemo.presentation.component.GameState
import com.hwpt.chesedemo.presentation.component.GameStatus
import com.hwpt.chesedemo.presentation.component.Player
import com.hwpt.chesedemo.presentation.component.Position
import com.hwpt.chesedemo.presentation.component.ChessBoard
import com.hwpt.chesedemo.presentation.theme.GradientEnd
import com.hwpt.chesedemo.presentation.theme.GradientStart
import com.hwpt.chesedemo.presentation.theme.strings
import com.hwpt.chesedemo.presentation.viewmodel.ChessGameViewModel

@Composable
fun BattleScreen(
    gameState: GameState,
    onPieceSelected: (Int, Int) -> Unit,
    onResign: () -> Unit,
    onDraw: () -> Unit,
    onSave: () -> Unit,
    onUndo: () -> Unit,
    canUndo: Boolean,
    modifier: Modifier = Modifier
) {
    val configuration = LocalConfiguration.current
    val screenWidth = configuration.screenWidthDp.dp
    val screenHeight = configuration.screenHeightDp.dp

    val isPortrait = configuration.screenHeightDp > configuration.screenWidthDp
    val isSmallScreen = screenWidth < 600.dp
    val isTablet = screenWidth >= 600.dp && screenWidth < 840.dp
    val isLargeTablet = screenWidth >= 840.dp

    Box(
        modifier = modifier
            .fillMaxSize()
            .background(
                brush = Brush.verticalGradient(
                    colors = listOf(GradientStart, GradientEnd)
                )
            )
    ) {
        if (isPortrait) {
            // 竖屏设备：统一的垂直布局，棋盘最大化
            PortraitLayout(
                gameState = gameState,
                onPieceSelected = onPieceSelected,
                onResign = onResign,
                onDraw = onDraw,
                onSave = onSave,
                onUndo = onUndo,
                canUndo = canUndo,
                isSmallScreen = isSmallScreen,
                isTablet = isTablet,
                isLargeTablet = isLargeTablet
            )
        } else {
            // 横屏设备：水平布局，棋盘最大化
            LandscapeLayout(
                gameState = gameState,
                onPieceSelected = onPieceSelected,
                onResign = onResign,
                onDraw = onDraw,
                onSave = onSave,
                onUndo = onUndo,
                canUndo = canUndo,
                isSmallScreen = isSmallScreen
            )
        }
    }
}

@Composable
private fun PortraitLayout(
    gameState: GameState,
    onPieceSelected: (Int, Int) -> Unit,
    onResign: () -> Unit,
    onDraw: () -> Unit,
    onSave: () -> Unit,
    onUndo: () -> Unit,
    canUndo: Boolean,
    isSmallScreen: Boolean,
    isTablet: Boolean,
    isLargeTablet: Boolean
) {
    val strings = strings()

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(
                horizontal = when {
                    isSmallScreen -> 12.dp
                    isTablet -> 20.dp
                    else -> 24.dp
                },
                vertical = 12.dp
            )
    ) {
        // 顶部：游戏头部（保持不变）
        CompactGameHeader(
            playerName = strings.you,
            aiName = gameState.selectedDifficulty?.nameKey ?: strings.aiOpponent,
            onResign = onResign,
            onDraw = onDraw,
            onSave = onSave,
            onUndo = onUndo,
            canUndo = canUndo,
            modifier = Modifier.fillMaxWidth()
        )

        Spacer(modifier = Modifier.height(16.dp))

        // 中间：最大化的棋盘区域
        Box(
            modifier = Modifier
                .weight(1f) // 给棋盘最大的权重
                .fillMaxWidth(),
            contentAlignment = Alignment.Center
        ) {
            ChessBoard(
                boardState = gameState.boardState,
                selectedPiece = gameState.selectedPiece,
                validMoves = gameState.validMoves,
                highlightedMove = gameState.highlightedMove, // 新增：传递高亮移动
                onPieceSelected = onPieceSelected,
                modifier = Modifier
                    .fillMaxWidth()
                    .aspectRatio(1f) // 确保棋盘是正方形

            )
        }

        Spacer(modifier = Modifier.height(2.dp))

        // 底部：走子记录和游戏信息
        BottomInfoPanel(
            gameState = gameState,
            modifier = Modifier
                .fillMaxWidth()
                .height(if (isSmallScreen) 180.dp else if (isTablet) 220.dp else 250.dp)
        )
    }
}

@Composable
private fun LandscapeLayout(
    gameState: GameState,
    onPieceSelected: (Int, Int) -> Unit,
    onResign: () -> Unit,
    onDraw: () -> Unit,
    onSave: () -> Unit,
    onUndo: () -> Unit,
    canUndo: Boolean,
    isSmallScreen: Boolean
) {
    val strings = strings()

    Row(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)
    ) {
        // 左侧：最大化的棋盘区域
        Box(
            modifier = Modifier
                .weight(if (isSmallScreen) 2f else 3f) // 给棋盘更多权重
                .fillMaxHeight(),
            contentAlignment = Alignment.Center
        ) {
            ChessBoard(
                boardState = gameState.boardState,
                selectedPiece = gameState.selectedPiece,
                validMoves = gameState.validMoves,
                highlightedMove = gameState.highlightedMove, // 新增：传递高亮移动
                onPieceSelected = onPieceSelected,
                modifier = Modifier.fillMaxHeight(0.95f) // 占据95%的可用高度
            )
        }

        Spacer(modifier = Modifier.width(16.dp))

        // 右侧：控制面板和走子记录
        Column(
            modifier = Modifier
                .weight(1f)
                .fillMaxHeight()
        ) {
            // 顶部：游戏头部
            CompactGameHeader(
                playerName = strings.you,
                aiName = gameState.selectedDifficulty?.nameKey ?: strings.aiOpponent,
                onResign = onResign,
                onDraw = onDraw,
                onSave = onSave,
                onUndo = onUndo,
                canUndo = canUndo,
                modifier = Modifier.fillMaxWidth()
            )

            Spacer(modifier = Modifier.height(16.dp))

            // 底部：走子记录
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f),
                colors = CardDefaults.cardColors(
                    containerColor = Color.White.copy(alpha = 0.1f)
                ),
                shape = androidx.compose.foundation.shape.RoundedCornerShape(15.dp)
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(16.dp)
                ) {
                    Text(
                        text = strings.moveHistory,
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold,
                        color = Color.White,
                        modifier = Modifier.padding(bottom = 8.dp)
                    )

                    MoveHistory(
                        moves = gameState.moveHistory,
                        modifier = Modifier
                            .fillMaxWidth()
                            .weight(1f)
                            .background(
                                color = Color.Black.copy(alpha = 0.2f),
                                shape = androidx.compose.foundation.shape.RoundedCornerShape(10.dp)
                            )
                            .padding(8.dp)
                    )
                }
            }
        }
    }
}

@Composable
private fun BottomInfoPanel(
    gameState: GameState,
    modifier: Modifier = Modifier
) {
    val strings = strings()

    Card(
        modifier = modifier,
        colors = CardDefaults.cardColors(
            containerColor = Color.White.copy(alpha = 0.1f)
        ),
        shape = androidx.compose.foundation.shape.RoundedCornerShape(12.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp)
        ) {
            // 走子记录（占据主要空间）
            Column(
                modifier = Modifier
                    .weight(2f)
                    .fillMaxHeight()
            ) {
                Text(
                    text = strings.moveHistory,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color.White,
                    modifier = Modifier.padding(bottom = 8.dp)
                )

                CompactMoveHistory(
                    moves = gameState.moveHistory,
                    modifier = Modifier
                        .weight(1f)
                        .fillMaxWidth()
                        .background(
                            color = Color.Black.copy(alpha = 0.2f),
                            shape = androidx.compose.foundation.shape.RoundedCornerShape(8.dp)
                        )
                        .padding(8.dp)
                )
            }

            Spacer(modifier = Modifier.width(16.dp))

            // 游戏信息（次要信息）
            Column(
                modifier = Modifier
                    .weight(1f)
                    .fillMaxHeight()
            ) {
                Text(
                    text = strings.gameInfo,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color.White,
                    modifier = Modifier.padding(bottom = 8.dp)
                )

                GameDetails(gameState = gameState)
            }
        }
    }
}

@Composable
private fun CompactGameHeader(
    playerName: String,
    aiName: String,
    onResign: () -> Unit,
    onDraw: () -> Unit,
    onSave: () -> Unit,
    onUndo: () -> Unit,
    canUndo: Boolean,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier,
        colors = CardDefaults.cardColors(
            containerColor = Color.White.copy(alpha = 0.1f)
        ),
        shape = androidx.compose.foundation.shape.RoundedCornerShape(12.dp)
    ) {
        Column(
            modifier = Modifier.padding(12.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // 玩家信息行
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                CompactPlayerInfo(name = playerName, emoji = "🧑")
                CompactPlayerInfo(name = aiName, emoji = "🤖")
            }

            Spacer(modifier = Modifier.height(8.dp))

            // 控制按钮
            GameControls(
                onResign = onResign,
                onDraw = onDraw,
                onSave = onSave,
                onUndo = onUndo,
                canUndo = canUndo
            )
        }
    }
}

@Composable
private fun CompactPlayerInfo(
    name: String,
    emoji: String,
    modifier: Modifier = Modifier
) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = modifier
    ) {
        Box(
            modifier = Modifier
                .size(32.dp)
                .background(
                    color = Color.White.copy(alpha = 0.2f),
                    shape = androidx.compose.foundation.shape.CircleShape
                ),
            contentAlignment = Alignment.Center
        ) {
            Text(text = emoji, fontSize = 16.sp)
        }

        Spacer(modifier = Modifier.size(6.dp))

        Text(
            text = name,
            fontSize = 14.sp,
            fontWeight = FontWeight.Bold,
            color = Color.White,
            maxLines = 1
        )
    }
}

@Composable
private fun CompactMoveHistory(
    moves: List<ChessMove>,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier.verticalScroll(rememberScrollState())
    ) {
        moves.forEach { move ->
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(4.dp)
            ) {
                Text(
                    text = "${move.moveNumber}.",
                    color = Color.White.copy(alpha = 0.7f),
                    fontSize = 12.sp,
                    modifier = Modifier.width(24.dp)
                )

                // 白方走子
                if (move.whiteMove != null) {
                    Text(
                        text = move.whiteMove,
                        color = Color.White,
                        fontSize = 12.sp,
                        modifier = Modifier
                            .weight(1f)
                            .background(
                                color = Color.White.copy(alpha = 0.1f),
                                shape = androidx.compose.foundation.shape.RoundedCornerShape(4.dp)
                            )
                            .padding(horizontal = 6.dp, vertical = 3.dp)
                    )
                } else {
                    Spacer(modifier = Modifier.weight(1f))
                }

                // 黑方走子
                if (move.blackMove != null) {
                    Text(
                        text = move.blackMove,
                        color = Color.White,
                        fontSize = 12.sp,
                        modifier = Modifier
                            .weight(1f)
                            .background(
                                color = Color.White.copy(alpha = 0.1f),
                                shape = androidx.compose.foundation.shape.RoundedCornerShape(4.dp)
                            )
                            .padding(horizontal = 6.dp, vertical = 3.dp)
                    )
                } else {
                    Spacer(modifier = Modifier.weight(1f))
                }
            }
        }
    }
}

@Composable
private fun MoveHistory(
    moves: List<ChessMove>,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier.verticalScroll(rememberScrollState())
    ) {
        moves.forEach { move ->
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(6.dp)
            ) {
                Text(
                    text = "${move.moveNumber}.",
                    color = Color.White.copy(alpha = 0.7f),
                    fontSize = 14.sp,
                    modifier = Modifier.width(30.dp)
                )

                // 白方走子
                if (move.whiteMove != null) {
                    Text(
                        text = move.whiteMove,
                        color = Color.White,
                        fontSize = 14.sp,
                        modifier = Modifier
                            .weight(1f)
                            .background(
                                color = Color.White.copy(alpha = 0.1f),
                                shape = androidx.compose.foundation.shape.RoundedCornerShape(5.dp)
                            )
                            .padding(horizontal = 8.dp, vertical = 4.dp)
                    )
                } else {
                    Spacer(modifier = Modifier.weight(1f))
                }

                // 黑方走子
                if (move.blackMove != null) {
                    Text(
                        text = move.blackMove,
                        color = Color.White,
                        fontSize = 14.sp,
                        modifier = Modifier
                            .weight(1f)
                            .background(
                                color = Color.White.copy(alpha = 0.1f),
                                shape = androidx.compose.foundation.shape.RoundedCornerShape(5.dp)
                            )
                            .padding(horizontal = 8.dp, vertical = 4.dp)
                    )
                } else {
                    Spacer(modifier = Modifier.weight(1f))
                }
            }
        }
    }
}

@Composable
private fun GameDetails(
    gameState: GameState
) {
    val strings = strings()

    Column {
        Text(
            text = "${strings.turn}: ${if (gameState.currentTurn == Player.WHITE) strings.white else strings.black}",
            color = Color.White,
            fontSize = 14.sp,
            modifier = Modifier.padding(bottom = 4.dp)
        )
        Text(
            text = "${strings.status}: ${getGameStatusText(gameState.gameStatus)}",
            color = Color.White,
            fontSize = 14.sp,
            modifier = Modifier.padding(bottom = 4.dp)
        )
        Text(
            text = "${strings.moveCount}: ${gameState.moveCount}",
            color = Color.White,
            fontSize = 14.sp
        )
    }
}

@Composable
private fun getGameStatusText(status: GameStatus): String {
    val strings = strings()
    return when (status) {
        GameStatus.IN_PROGRESS -> strings.inProgress
        GameStatus.CHECK -> strings.check
        GameStatus.CHECKMATE -> strings.checkmate
        GameStatus.STALEMATE -> strings.stalemate
        GameStatus.RESIGNED -> strings.resignation
        GameStatus.DRAW -> strings.drawAgreed
    }
}

@Composable
fun ChessApp(
    navController: NavHostController,
    viewModel: ChessGameViewModel = hiltViewModel()
) {
    val gameState = viewModel.gameState.collectAsState().value

    Box(modifier = Modifier.fillMaxSize()) {
        when (gameState.currentScreen) {
            ChessScreen.DIFFICULTY_SELECTION -> {
                DifficultySelectionScreen(
                    onDifficultySelected = { difficulty ->
                        println("DEBUG: Difficulty selected: ${difficulty.nameKey}")
                        viewModel.selectDifficulty(difficulty)
                    }
                )
            }

            ChessScreen.GAME_BOARD -> {
                BattleScreen(
                    gameState = gameState,
                    onPieceSelected = { row, col ->
                        println("DEBUG: Piece selected at ($row, $col), current turn: ${gameState.currentTurn}")
                        viewModel.selectPiece(Position(row, col))
                    },
                    onResign = {
                        println("DEBUG: Resign clicked")
                        viewModel.resign()
                    },
                    onDraw = {
                        println("DEBUG: Draw clicked")
                        viewModel.requestDraw()
                    },
                    onSave = {
                        println("DEBUG: Save clicked")
                        viewModel.saveGame()
                    },
                    onUndo = {
                        println("DEBUG: Undo clicked")
                        viewModel.undoMove()
                    },
                    canUndo = viewModel.canUndo()
                )
            }
        }

        if (gameState.showGameOverDialog) {
            GameOverDialog(
                title = gameState.gameResult?.title ?: strings().gameOver,
                message = gameState.gameResult?.message ?: "",
                winner = gameState.gameResult?.winner,
                onSavePgn = {
                    viewModel.saveGame()
                    viewModel.acknowledgeGameOver()
                },
                onNewGame = {
                    viewModel.newGame()
                }
            )
        }
    }
}

@Composable
fun GameOverDialog(
    title: String,
    message: String,
    winner: Player? = null,
    onSavePgn: () -> Unit,
    onNewGame: () -> Unit,
) {
    val strings = strings()

    Dialog(
        onDismissRequest = { /* 不允许点击外部关闭 */ }
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .background(
                    brush = Brush.verticalGradient(
                        colors = listOf(GradientStart, GradientEnd)
                    ),
                    shape = RoundedCornerShape(20.dp)
                )
                .padding(24.dp)
        ) {
            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
                modifier = Modifier.fillMaxWidth()
            ) {
                // 显示胜利者图标
                winner?.let {
                    Text(
                        text = if (winner == Player.WHITE) "👑" else "🏆",
                        fontSize = 48.sp,
                        modifier = Modifier.padding(bottom = 8.dp)
                    )
                } ?: run {
                    Text(
                        text = "🤝",
                        fontSize = 48.sp,
                        modifier = Modifier.padding(bottom = 8.dp)
                    )
                }

                // 标题
                Text(
                    text = title,
                    fontSize = 24.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color.White,
                    textAlign = TextAlign.Center,
                    modifier = Modifier.padding(bottom = 8.dp)
                )

                // 消息
                Text(
                    text = message,
                    fontSize = 16.sp,
                    color = Color.White.copy(alpha = 0.9f),
                    textAlign = TextAlign.Center,
                    modifier = Modifier.padding(bottom = 24.dp)
                )

                // 按钮区域
                Row(
                    horizontalArrangement = Arrangement.spacedBy(12.dp),
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Button(
                        onClick = onSavePgn,
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color.White.copy(alpha = 0.2f)
                        ),
                        modifier = Modifier.weight(1f)
                    ) {
                        Text(
                            text = strings.savePgn,
                            color = Color.White,
                            fontSize = 14.sp
                        )
                    }

                    Button(
                        onClick = onNewGame,
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color(0xFF4CAF50)
                        ),
                        modifier = Modifier.weight(1f)
                    ) {
                        Text(
                            text = strings.newGame,
                            color = Color.White,
                            fontSize = 14.sp
                        )
                    }
                }
            }
        }
    }
}

@Composable
fun GameControls(
    onResign: () -> Unit,
    onDraw: () -> Unit,
    onSave: () -> Unit,
    onUndo: () -> Unit,
    canUndo: Boolean,
    modifier: Modifier = Modifier
) {
    val strings = strings() // 获取多语言字符串

    Row(
        horizontalArrangement = Arrangement.spacedBy(8.dp),
        modifier = modifier.fillMaxWidth()
    ) {
        Button(
            onClick = onUndo,
            enabled = canUndo,
            colors = ButtonDefaults.buttonColors(
                containerColor = if (canUndo) Color.White.copy(alpha = 0.2f) else Color.Gray.copy(alpha = 0.2f)
            ),
            modifier = Modifier.weight(1f)
        ) {
            Text(
                text = strings.undo,
                color = if (canUndo) Color.White else Color.White.copy(alpha = 0.5f)
            )
        }
        Button(
            onClick = onResign,
            colors = ButtonDefaults.buttonColors(
                containerColor = Color.White.copy(alpha = 0.2f)
            ),
            modifier = Modifier.weight(1f)
        ) {
            Text(text = strings.resign, color = Color.White)
        }
        Button(
            onClick = onDraw,
            colors = ButtonDefaults.buttonColors(
                containerColor = Color.White.copy(alpha = 0.2f)
            ),
            modifier = Modifier.weight(1f)
        ) {
            Text(text = strings.draw, color = Color.White)
        }
        Button(
            onClick = onSave,
            colors = ButtonDefaults.buttonColors(
                containerColor = Color.White.copy(alpha = 0.2f)
            ),
            modifier = Modifier.weight(1f)
        ) {
            Text(text = strings.saveGame, color = Color.White)
        }
    }
}